//
//  AccountTool.m
//  CMJWeibo
//
//  Created by BH on 15/12/9.
//
//

#import "AccountTool.h"
#import "HttpTool.h"
#import "MJExtension.h"

#define AccountFilepath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"account.data"]

@implementation AccountTool

/**
 *  归档
 */
+(void)saveAccount:(Account *)account
{
    [NSKeyedArchiver archiveRootObject:account toFile:AccountFilepath];
}

//获取当前版本
+(Account *)account
{
    // 判断账号(accessToken)是否过期
    Account *account = [NSKeyedUnarchiver unarchiveObjectWithFile:AccountFilepath];
    
    //获取当前时间
    NSDate *now = [NSDate date];
    // 比较当前时间 和 账号的过期时间
    if ([account.expire_time compare:now] == NSOrderedAscending) {
        //过期
        return nil;
    }
    
    return account;
}

+(void)accessTokenWithParam:(AccessTokenParam *)param success:(void (^)(AccessTokenResult *))success failure:(void (^)(NSError *))failure
{
    [HttpTool postWithURL:@"https://api.weibo.com/oauth2/access_token" params:param.keyValues success:^(id json) {
        if (success) {
            NSLog(@"%@",json);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:nil];
            AccessTokenResult *result = [AccessTokenResult objectWithKeyValues:dict];
            success(result);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end
